<template>
  <flexbox justify="flex-start" class="filtrate-content">
    <flexbox justify="flex-start" class="title-box">
      <div class="icon-box">
        <span class="wk wk-my-task icon"/>
      </div>
      <span class="text">{{ title }}</span>
    </flexbox>
    <template v-if="filterViewShowFlag">
      <TimeTypeSelect v-if="!yearSelectShowFlag" @change="timeTypeChange"/>
      <!-- 展示年筛选 -->
      <el-date-picker v-if="yearSelectShowFlag" v-model="selectedYear"
                      :clearable="false"
                      :disabled-date="checkDateCanSelect"
                      type="year"
                      value-format="YYYY"
                      placeholder="选择年"/>
      <!-- 展示部门筛选 -->
      <el-select v-if="whetherUserCanSelect" v-model="selectByDeptOrUser">
        <template v-for="item in [{label:'按部门', value:1},{label:'按员工', value:2}]" :key="item.value">
          <el-option :label="item.label" :value="item.value"/>
        </template>
      </el-select>

      <WkDepSelect v-if="selectByDeptOrUser == 1"
                   v-model:deptSelected="deptSelectedValue"
                   radio
                   placeholder="选择部门（默认为本部门及下属部门）"
                   class="wk-dep-select"/>
      <!--todo whf 下面的wkUserSelect应该需要传入userListInDept，d-->
      <WkUserSelect v-if="selectByDeptOrUser == 2 && whetherUserCanSelect"
                    v-model:userSelected="userSelectedValue"
                    radio
                    class="wk-user-select" placeholder="选择员工（默认为本人及下属）"/>
      <!-- 展示商机状态筛选 -->
      <el-select v-if="businessSelectShowFlag" v-model="businessStatusSelectedValue" placeholder="商机组">
        <el-option v-for="item in businessOptionList" :key="item.typeId"
                   :label="item.name" :value="item.typeId"/>
      </el-select>
      <!--todo whf el-cascader中change-on-select是控制是否允许选择任意层级的-->
      <el-cascader v-if="productSelectShowFlag" :options="productOptionList"
                   :show-all-levels="false"
                   :props="{children: 'children',label: 'label',value: 'categoryId'}"
                   v-model="productSelectedValue"
                   style="width: 100%;"
                   change-on-select/>
      <el-select v-if="customSelectShowFlag" v-model="customSelectedValue" @change="customSelectChange">
        <el-option v-for="item in customOptionList" :key="item.value"
                   :label="item.name"
                   :value="item.value"/>
      </el-select>
      <slot name="append"/>
      <el-button type="primary" @click="searchFiltrateValue()">搜索</el-button>
      <slot/>
    </template>
  </flexbox>
</template>


<script setup>
import WkDepSelect from '/src/szcomponent/NewCom/SzDeptUserComp/WkDepSelect'
import WkUserSelect from '/src/szcomponent/NewCom/SzDeptUserComp/WkUserSelect'
import TimeTypeSelect from '/src/szcomponent/TimeTypeSelect'
import {
  getUserByDeptIdAPI
} from '/src/api/common'
import {crmBusinessStatusListAPI} from '/src/api/crm/business'
import {productCategoryIndexAPI} from '/src/api/admin/crm'
import moment from "moment";


defineOptions({
  name: 'FiltrateHandleView', // 筛选条件
})

const props = defineProps({
  // 模块类型  暂无意义 可不传
  moduleType: {
    type: String
  },
  // 模块标题
  title: {
    type: String,
    default: ''
  },
  filterViewShowFlag: {
    default: true,
    type: Boolean
  },
  // 是否展示年
  yearSelectShowFlag: {
    default: false,
    type: Boolean
  },
  // 是否展示商机状态筛选
  businessSelectShowFlag: {
    default: false,
    type: Boolean
  },
  // 员工选择窗口是否可显示
  whetherUserCanSelect: {
    default: true,
    type: Boolean
  },
  customSelectShowFlag: {
    default: false,
    type: Boolean
  },
  customOptionDefaultValue: '',
  // 自定义的展示选项列表
  customOptionList: {
    default: () => {
      return []
    },
    type: Array
  },
  // 是否展示产品类别选择窗口
  productSelectShowFlag: {
    default: false,
    type: Boolean
  }
})

const optionData = reactive({

  selectedYear: '',

  /** 时间类型值 */
  selectedTimeType: {},


  /** 部门选择解析数据 */
  // structuresProps: {
  //   children: 'children',
  //   label: 'label',
  //   value: 'id'
  // },
  selectByDeptOrUser: 1, // 1 是部门 2 是员工
  // deptList: [], // 部门列表
  deptSelectedValue: '',
  /** 指定部门下的用户列表 */
  userListInDept: [],
  userSelectedValue: '',


  /** 可选的商机状态 */
  businessOptionList: [],
  // 选择的商机数据
  businessStatusSelectedValue: '',
  /** 产品类别 */
  productSelectedValue: [],
  productOptionList: [],
  // 图标类型
  customSelectedValue: ''
})

const {
  selectedYear,
  selectedTimeType,
  selectByDeptOrUser,
  deptSelectedValue,
  userListInDept,
  userSelectedValue,
  businessOptionList,
  businessStatusSelectedValue,
  productSelectedValue,
  productOptionList,
  customSelectedValue
} = toRefs(optionData)


// 年筛选
const checkDateCanSelect = (time) => {
  // disabledDate(time) {
  console.log("time", time)
  return time.getTime() > Date.now()
}

const emits = defineEmits(['load', 'typeChange', 'search'])

onMounted(() => {
  // 自定义选择项 默认值
  if (props.customSelectShowFlag) {
    optionData.customSelectedValue = props.customOptionDefaultValue
  }
  if (props.yearSelectShowFlag) {
    optionData.selectedYear = moment(new Date())
        .year()
        .toString()
    console.log("optionData.yearValue", optionData.yearValue)
  }

  emits('load')
  // 展示员工 不展示新的员工部门筛选效果
  if (props.businessSelectShowFlag) {
    getBusinessStatusList(() => {
      searchFiltrateValue()
    })
  } else {
    searchFiltrateValue()
  }

  if (props.productSelectShowFlag) {
    getProductCategoryIndex()
  }
})


// 选择更改
function customSelectChange() {
  emits('customValueChange', optionData.customSelectedValue)
}

// 类型选择
function timeTypeChange(data) {
  console.log("timeTypeChange", data)
  optionData.selectedTimeType = data
}

/** 部门更改 */
function structuresValueChange(data) {
  // 展示员工筛选，执行更新逻辑
  if (props.whetherUserCanSelect) {
    optionData.userSelectedValue = ''
    optionData.userListInDept = []
    getUserList() // 更新员工列表
  }
}

/** 部门下员工 */
function getUserList() {
  let params = {}
  params.deptId = optionData.deptSelectedValue
  getUserByDeptIdAPI(params).then(res => {
    optionData.userListInDept = res.data.data
  }).catch(() => {
  })
}

/** 商机阶段 */
function getBusinessStatusList(result) {
  crmBusinessStatusListAPI().then(res => {
    const list = res.data.data || []
    optionData.businessOptionList = list.filter(item => {
      return item.status === 1
    })
    if (optionData.businessOptionList.length > 0) {
      optionData.businessStatusSelectedValue = optionData.businessOptionList[0].typeId
    }
    result(true)
  }).catch(() => {
  })
}

/** 获取产品分类数据 */
function getProductCategoryIndex() {
  productCategoryIndexAPI({
    type: 'tree'
  }).then(res => {
    optionData.productOptionList = res.data.data
  }).catch(() => {
  })
}

function searchFiltrateValue() {
  const params = {}
  if (props.whetherUserCanSelect) {
    if (optionData.selectByDeptOrUser == 1) {
      // 传递过来的是数组，
      params.deptId = optionData.deptSelectedValue[0]
    }
  } else {
    params.deptId = optionData.deptSelectedValue[0]
  }

  if (props.whetherUserCanSelect) {
    params.isUser = optionData.selectByDeptOrUser == 2 ? 1 : 0
  }

  // 展示员工，返回员工参数
  if (props.whetherUserCanSelect) {
    if (optionData.selectByDeptOrUser == 2) {
      params.userId = optionData.userSelectedValue
    }
  }

  // 展示商机状态 返回商机状态参数
  if (props.businessSelectShowFlag) {
    params.typeId = optionData.businessStatusSelectedValue
  }

  if (props.productSelectShowFlag) {
    params.categoryId =
        optionData.productSelectedValue.length > 0
            ? optionData.productSelectedValue[optionData.productSelectedValue.length - 1]
            : ''
  }

  // 展示年和展示时间段类型不同时出现
  if (props.yearSelectShowFlag) {
    params.year = optionData.selectedYear
  } else {
    if (optionData.selectedTimeType.type == 'custom') {
      params.startTime = optionData.selectedTimeType.startTime
      params.endTime = optionData.selectedTimeType.endTime
    } else {
      params.type = optionData.selectedTimeType.value
    }
  }
  console.log("params", params)
  emits('search', params)
}

</script>

<style lang="scss" scoped>
.filtrate-content {
  padding: 15px 20px 5px 20px;

  .title-box {
    width: 220px;
    display: flex;

    .icon-box {
      width: 34px;
      height: 34px;
      text-align: center;
      line-height: 34px;
      color: $xr-color-primary;
      background-color: #dfe8ff;
      border-radius: 50%;
      margin-right: 10px;
    }

    .text {
      font-size: 17px;
      font-weight: bold;
    }
  }

  .el-date-editor {
    width: 130px;
    margin-right: 15px;
  }

  .el-cascader {
    width: 130px;
    margin-right: 15px;
  }

  .el-select {
    width: 120px;
    margin-right: 15px;
  }

  .el-cascader {
    width: 120px !important;
    margin-right: 15px;
  }

  .wk-user-select,
  .wk-dep-select {
    text-align: left;
    width: 235px;
    margin-right: 15px;
  }
}

// 时间选择
.type-popper {
  .type-content {
    height: 250px;
    overflow-y: auto;

    .type-content-item {
      height: 34px;
      line-height: 34px;
      padding: 0 20px;
      color: #606266;
      position: relative;
      cursor: pointer;

      .mark {
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: $xr-border-radius-base;
        margin-right: 5px;
        background-color: transparent;
      }
    }

    .selected {
      color: #409eff;
      font-weight: 700;

      .mark {
        background-color: #409eff;
      }
    }

    .type-content-item:hover {
      background-color: #f5f7fa;
    }
  }

  .type-content-custom {
    padding: 5px 20px 10px;
    position: relative;
    overflow: hidden;

    .el-date-editor {
      width: 100%;
      margin-bottom: 8px;
    }

    button {
      float: right;
    }
  }
}
</style>
